﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Dss.Data;

namespace Dss.Methods
{
     public class Member
    {
         public Member() {

             cecbContext = new DSSEntities();
         }

          // get clas objects to use in insert member method
         DSSEntities cecbContext;
         Employee employee;
         Employee_ContactNo employeeContactNo;
         Employee_Email  employeeEmail;

         // insert member method
         public  bool InsertMember( String fname, String lname, String designation, String nic, Int32 contactNo, String email) 
         {
             bool IsInserted = false;
             try
             {
                 String reference = getNewMemberReference();
                 employee = new Employee();
                 employee.EmpReference = reference;
                 employee.EmpfName = fname;
                 employee.EmplName = lname;
                 employee.EmpDesignation = designation;
                 employee.EmpNic = nic;
                 employee.EmpDate = DateTime.Now;
                 cecbContext.AddToEmployees(employee);
                 cecbContext.SaveChanges();

                 // insert data to the EmployeeContact table
                 employeeContactNo = new Employee_ContactNo();
                 employeeContactNo.Emp_Reference = reference;
                 employeeContactNo.Emp_ContactNo = contactNo;
                 cecbContext.AddToEmployee_ContactNo(employeeContactNo);
                 cecbContext.SaveChanges();

                 // insert data to the Employee email table
                 employeeEmail = new Employee_Email();
                 employeeEmail.Emp_Reference = reference;
                 employeeEmail.Emp_Email = email;
                 cecbContext.AddToEmployee_Email(employeeEmail);
                 cecbContext.SaveChanges();

                 IsInserted = true;
             }
             catch (Exception)
             {

                 IsInserted = false;
             }


             return IsInserted;
         }

         // generate the member refarance
         public  String getNewMemberReference() 
         {
              
             var idKey = (from c in cecbContext.Employees
                          orderby c.EmpID descending
                          select c).First();

             String id = idKey.EmpReference.ToString();                        
             int sub = int.Parse(id.Substring(3)) +1;       
             String newId = "Mem" + sub;
             return newId.ToString();
         }

    }
}
